import pyglet
import AStar
import time
import TreeAA
from project_util import *

A = None
B = None
i = None

vehicle_pointer_image = pyglet.image.load('vehicle_pointer.png')
vehicle_pointer = pyglet.sprite.Sprite(vehicle_pointer_image, -50, -50)

occupied_pointer_image = pyglet.image.load('occupied_pointer.png')
occupied_cursor = pyglet.window.ImageMouseCursor(occupied_pointer_image, 50, 50)

free_pointer_image = pyglet.image.load('free_pointer.png')
free_cursor = pyglet.window.ImageMouseCursor(free_pointer_image, 50, 50)

pmojave = pyglet.image.load('mojave.tiff')
bg = pyglet.sprite.Sprite(pmojave)
window = pyglet.window.Window(width=pmojave.width, height=pmojave.height)


@window.event
def on_draw():
    bg.draw()
    vehicle_pointer.draw()


@window.event
def on_mouse_press(x, y, button, modifiers):
    global A, B, i, vehicle_pointer
    B = None
    i = None
    if not occupied((x, y)):
        A = (x, y)
        print 'From: ', A
        vehicle_pointer.x, vehicle_pointer.y = to_screen(A, vehicle_pointer)


@window.event
def on_mouse_release(x, y, buttons, modifiers):
    global B, i
    B = (x, y)
    print 'To: ', B
    if A is not None and not occupied(B):
        i = AStar.astar(A, B)


@window.event
def on_mouse_motion(x, y, dx, dy):
    if occupied((x, y)):
        window.set_mouse_cursor(occupied_cursor)
    else:
        window.set_mouse_cursor(free_cursor)


@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    if occupied((x, y)):
        window.set_mouse_cursor(occupied_cursor)
    else:
        window.set_mouse_cursor(free_cursor)


def update(secs):
    global A, B, i, vehicle_pointer
    if B is not None and i is not None:
        try:
            v = i.next()
            if occupied(v):
                real = to_coord((vehicle_pointer.x, vehicle_pointer.y), vehicle_pointer)
                t0 = time.time()
                i = AStar.astar(real, B)
                print time.time() - t0
                v = i.next()
            vehicle_pointer.x, vehicle_pointer.y = to_screen(v, vehicle_pointer)
        except StopIteration:
            A = None
            B = None
            i = None


if __name__ == '__main__':
    pyglet.gl.glClearColor(230.0/255.0, 180.0/255.0, 130.0/255.0, 1)
    pyglet.clock.schedule(update)
    pyglet.app.run()